package org.example.springbirthday.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.example.springbirthday.config.CaptchaProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 九转苍翎
 * Date: 2025/8/12
 * Time: 00:10
 */
@Slf4j
@RequestMapping("/captcha")
@RestController
public class CaptchaController {
    @Autowired
    private CaptchaProperties captchaProperties;
    public final static long delay = 60_000L;
    //
    @RequestMapping("/get")
    public void getCaptcha(HttpSession session, HttpServletResponse response) {
        log.info("getCaptcha");
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());
        //设置返回类型
        response.setContentType("image/jpeg");
        //禁止缓存
        response.setHeader("Pragma", "No-cache");
        try {
            lineCaptcha.write(response.getOutputStream());
            //保存code
            session.setAttribute(captchaProperties.getSession().getKey(), lineCaptcha.getCode());
            //保存当前时间
            session.setAttribute(captchaProperties.getSession().getDate(), System.currentTimeMillis());
            response.getOutputStream().close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
